using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.PurchasingManagement.PurchaseOrders;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseArrivalNotes;

namespace RBAC.Write.Api.Application.Handler.ERP.PurchasingManagement.PurchaseArrivalNotes
{
    /// <summary>
    /// 批量逻辑删除采购到货单
    /// </summary>
    public class BatchDeletePurchaseArrivalNotesCommandHandler : IRequestHandler<BatchDeletePurchaseArrivalNotesCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ArrivalOrderInfo> _repo;
        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<BatchDeletePurchaseArrivalNotesCommandHandler> _logger;

        public BatchDeletePurchaseArrivalNotesCommandHandler(
            IBaseRepository<ArrivalOrderInfo> repo,
            IDbConnectionFactory connectionFactory,
            ILogger<BatchDeletePurchaseArrivalNotesCommandHandler> logger)
        {
            _repo = repo;
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchDeletePurchaseArrivalNotesCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "未指定要删除的ID", Data = 0 });
                }

                using var conn = _connectionFactory.CreateConnectionWithRetry();
                using var tran = conn.BeginTransaction();

                // 主表逻辑删除（ArrivalOrderInfo 使用 IsDeleted 字段）
                var sqlMain = "UPDATE ArrivalOrderInfo SET IsDeleted = 1 WHERE Id IN @Ids AND IsDeleted = 0";
                var affectedMain = conn.Execute(sqlMain, new { request.Ids }, tran);

                // 明细表逻辑删除（ArrivalOrderMaterialInfo 使用 IsDel 字段）
                var sqlDetail = "UPDATE ArrivalOrderMaterialInfo SET IsDel = 1 WHERE ArrivalOrderId IN @Ids AND IsDel = 0";
                var affectedDetail = conn.Execute(sqlDetail, new { request.Ids }, tran);

                tran.Commit();

                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Success,
                    Msg = "批量删除成功",
                    Data = affectedMain
                });
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "批量删除采购到货单失败: {Message}", ex.Message);
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = "批量删除失败",
                    Data = 0
                });
            }
        }
    }
}
